<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 登录页面
 *
 * @author      Eden
 * @datetime    2016/11/24 21:56
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Login extends CI_Controller
{
    // 密码最小长度
    const PASSWORD_MIN_LEN = 6;

    // 密码最大长度
    const PASSWORD_MAX_LEN = 18;

    /**
     * 登录界面
     */
    public function index()
    {
        if ($this->session->has_userdata('adminDetail')) {
            redirect("/home");
        } else {
            $this->load->view('admin/login/index.html');
        }
    }

    /**
     * 检查登录
     */
    public function checkLogin()
    {
        $send['state'] = false;
        $type = $this->input->post('type');
        $email = $this->input->post('email');
        $password = $this->input->post('password');

        do {

            // 请求是否非法
            if ($this->input->method(TRUE) !== 'POST') {
                $send['error'] = '非法请求';
                break;
            }

            // 验证数据的合法性
            if (empty($email) || empty($password)
                || !filter_var($email, FILTER_VALIDATE_EMAIL)
                || strlen($password) < self::PASSWORD_MIN_LEN
                || strlen($password) > self::PASSWORD_MAX_LEN) {
                $send['error'] = '账号或密码错误';
                break;
            }

            $this->load->model('admin/login/Login_Model', 'login');
            $check = $this->login->checkAdmin($email, $password);

            if (!$check) {
                $err = $this->login->getError();
                $send['error'] = empty($err) ? '用户名或密码错误' : $err;
                break;
            }

            $role = $type == 'admin' ? 'admin' : 'base';

            $detail = $this->login->getDetail();
            if ($type == 'base' && $detail['baseId'] == 0) {
               $send['error'] = '您不是商户用户，请确认登录类型';
               break;
            }

            if ($type != 'base' && $detail['baseId'] > 0) {
                $send['error'] = '您不是管理员用户，请确认登录类型';
                break;
            }

            // 保存到 Session
            $this->session->set_userdata('adminDetail', $detail);
            $this->session->set_userdata('role', $role);

            if ($role == 'base') {
                $this->session->set_userdata('baseId', $this->login->getBaseID());
            }

            $send['state'] = true;

        } while(false);

        $this->output->send($send);
    }

    public function logout()
    {
        if ($this->session->has_userdata('adminDetail')) {
            $this->session->unset_userdata('adminDetail');
            $this->session->unset_userdata('role');
            $this->session->unset_userdata('baseId');
        }
        redirect('login');
    }

}
